//
//  SinaStatusPictureView.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/10/28.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit
import SDWebImage
private let statusCellID = "statusCellID"

//cell 间距
let cellMargin: CGFloat = 5
//宽高
let cellWH = CGFloat(Int((SinaScreenW - 20 - cellMargin*2)/3))

class SinaStatusPictureView: UICollectionView {
    
    //MARK: - 定义属性,供外界赋值
    var picUrls:[SinaPictureInfoModel]?{
        didSet{
            //赋值
            countLabel.text = "\(picUrls?.count ?? 0)"
            
            //得到配图的大小
            //let size = dealScaleSize(count: picUrls?.count ?? 0)
            //设置约束 -> 注意是更新约束
            //self.snp_updateConstraints { (make) in
              ///  make.size.equalTo(size)
            //}//
            dealScaleSize(count: picUrls?.count ?? 0)
            //一定要记得刷新 UI
            reloadData()
        }
    }

    //计算配图的 size
    func dealScaleSize(count: Int){
        
        //如果是单张图片
        if count == 1 {
            //获取 key
            let key = picUrls?.first?.thumbnail_pic ?? ""
            //从缓存中获取 image
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key)
            
            if image != nil {
                let result = image!.size
                //更新约束
                self.snp_updateConstraints(closure: { (make) in
                    make.size.equalTo(result)
                })
                layoutIfNeeded()
                //设置 itemSize
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = result
                
                return
            }
        }
        //行数,列数
        let col = count > 3 ? 3 : count
        let row = (count - 1)/3 + 1
      
        //得到最后的宽和高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1)*cellMargin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMargin
        //更新约束
        self.snp_updateConstraints(closure: { (make) in
            make.size.equalTo(CGSize(width: w, height: h))
        })
        layoutIfNeeded()
        //设置 itemSize
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        layout.minimumLineSpacing = cellMargin
        layout.minimumInteritemSpacing = cellMargin

        
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 设置视图
    private func setupUI() {
        
//        //得到 layout
//        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
//        //设置 itemSize
////        layout.itemSize = CGSize(width: cellWH, height: cellWH)
//        //设置间距
//        layout.minimumLineSpacing = cellMargin
//        layout.minimumInteritemSpacing = cellMargin
        
        //设置数据源
        dataSource = self
        //注册 cell
        register(SinaStatusPictureViewCell.self, forCellWithReuseIdentifier: statusCellID)
        //添加控件
        addSubview(countLabel)
        //添加约束
        countLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    //MARK: - 懒加载控件
    private lazy var countLabel: UILabel = {
        let lab = UILabel(text: "", fontSize: 30, textColor: UIColor.red)
        lab.textAlignment = .center
        return lab
    }()
}
extension SinaStatusPictureView: UICollectionViewDataSource{
   
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: statusCellID, for: indexPath) as! SinaStatusPictureViewCell
        
        //赋值
        cell.picUrl = picUrls![indexPath.item]
        return cell
    }
}
//MARK: - 自定义配图的 cell
class SinaStatusPictureViewCell: UICollectionViewCell {
    
    //定义属性,供外界赋值
    var picUrl: SinaPictureInfoModel?{
        didSet{
            bgImageView.hm_setImage(withUrlString: picUrl?.thumbnail_pic, placeholderImgName: "kWBLLGY")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        //添加控件
        contentView.addSubview(bgImageView)
        //添加约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
    }
    //MARK: - 懒加载控件
    private lazy var bgImageView:UIImageView = {
        let view = UIImageView(imgName: "kWBLLGY")
        view.contentMode = .scaleAspectFill
        view.layer.masksToBounds = true
        return view
    }()
}
